package be.donovan.gui.helper.components;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import javax.swing.table.TableColumn;

import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.table.TableColumnExt;

public class TableConfiguration {
	public static String prefRoot = "quebak/tables_config/";

	@SuppressWarnings("unchecked")
	public static void saveTableConfiguration(JXTable table, String tableName) {
		List<TableColumn> cols = table.getColumns(true);
		Preferences rootPref = Preferences.userRoot().node(prefRoot + tableName);
		TableColumnExt tcExt;
		Preferences p;
		for (TableColumn tc : cols) {
			tcExt = table.getColumnExt(tc.getHeaderValue());
			p = rootPref.node("" + tc.getHeaderValue());
			p.putBoolean("visible", tcExt.isVisible());
			p.putInt("width", tcExt.getWidth());
			p.putInt("position", table.convertColumnIndexToView(tcExt.getModelIndex()));
		}
		try {
			rootPref.flush();
		} catch (BackingStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public static void loadTableConfiguration(JXTable table, String tableName) {
		List<TableColumn> cols = table.getColumns(true);
		Map<Integer, String> colsOrder = new HashMap<Integer, String>();
		try {
			if (Preferences.userRoot().nodeExists(prefRoot + tableName)) {
				Preferences rootPref = Preferences.userRoot().node(prefRoot + tableName);
				TableColumnExt tcExt;
				Preferences p;
				int position = -1;
				for (TableColumn tc : cols) {
					tcExt = table.getColumnExt(tc.getHeaderValue());
					p = rootPref.node("" + tc.getHeaderValue());
					tcExt.setVisible(p.getBoolean("visible", true));
					tcExt.setWidth(p.getInt("width", tcExt.getWidth()));
					tcExt.setPreferredWidth(p.getInt("width", tcExt.getWidth()));
					position = p.getInt("position", -1);
					if (position >= 0) {
						colsOrder.put(position, tcExt.getHeaderValue().toString());
					}
				}
				String[] colsOrderName = new String[colsOrder.size()];
				for (int i = 0; i < colsOrder.size(); i++) {
					colsOrderName[i] = colsOrder.get(i);
				}
				table.setColumnSequence(colsOrderName);
			}
		} catch (BackingStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
